import React from 'react';
import { connect } from 'dva'

import styles from './style/Statistics.less'
import Title from 'components/Title'

import { Tabs, ActivityIndicator } from 'antd-mobile';
import { config } from 'utils'
const { scada } = config;
const {
  Token,
  realtimetemplate
} = scada;

const activeTab = 0;

@connect(({ monitor }) => ({ ...monitor }))
class Statistics extends React.Component {
  List = realtimetemplate;

  constructor(props) {
    super(props);

    let tab = {};
    if (Array.isArray(this.List) && this.List.length > 0) {
      tab = this.List[activeTab];
    }

    this.state = {
      tab,       // 当前
      activeTab,
      columns: [],   // 列表表头
      loading: true,
    }
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    await this.setDateStatistics()
  }

  setDateStatistics = async () => {
    await this.queryData();
  }

  queryData = async () => {
    const { state } = this;
    const { tab } = state;
    const { serverType } = tab;

    // hd_station_list时，直接list请求
    if (serverType === "hd_station_list") {
      await this.queryStationList(tab)
    } else {
      // 1. 先调用 queryUbizTpl，获取 columns 字段信息
      await this.queryUbizTpl(tab).then((result) => {
        // 2. 再 获取的columns信息传入下次请求
        const { columns } = result;
        this.setState({
          columns
        }, async () => {
          await this.queryScadaTpl(tab)
        })
      })
    }
  }

  // station list
  queryStationList = async (param) => {
    const { value, payload } = param;
    let server = { type: 'monitor/queryList' }
    Object.assign(payload, { Token, value })
    Object.assign(server, { payload })
    await this.props.dispatch(server)
    .then(() => {
      this.setState({
        loading: this.props[`ListLoading${value}`]
      })
    })
  }
  // Ubiz Tpl
  queryUbizTpl = async (param) => {
    const { value } = param;
    let server = { type: 'monitor/queryUbizTpl' };
    const payload = {
      Token, "conditions": [{ Field: "code", Operate: "=", Value: value, Relation: "and" }], order: [], size: 20, index: 1
    }
    Object.assign(payload, { value })
    Object.assign(server, { payload })
    // 注意：return后，可以回调哦！
    return await this.props.dispatch(server)
  }
  // Scada Tpl
  queryScadaTpl = async (param) => {
    const { columns } = this.state;
    const { value, payload } = param;

    // 处理 columns 开始
    let columnsParams = {}
    columns.forEach(column => {
      const { id, attribute, type } = column;
      // columns值：attribute 和 type的拼接
      let cols = attribute;
      Object.assign(cols, { "_type": type })
      // columns键名：'C' + id 拼接
      columnsParams[`C${id}`] = cols;
    })
    // 处理 columns 结束

    Object.assign(payload, { Token, value, columns: columnsParams });
    await this.props.dispatch({
      type: 'monitor/queryScadaTpl',
      payload
    }).then(() => {
      this.setState({
        loading: this.props[`ScadaTplLoading${value}`]
      })
    })
  }

  renderContent = () => {
    const { props, state } = this;
    const { tab, loading } = state;
    const { value, serverType } = tab;

    let children = null;
    if(loading){
      children = (<div className="loading-placeholder"><ActivityIndicator size="large" animating /></div>);
    }else{
      if (serverType === "hd_station_list") {
        const dataResource = props[`ListResource${value}`];
        try {
          let child = null;
          if(dataResource){
            const { Sensors, Station } = dataResource;
            if(Array.isArray(Sensors)){
              child = Sensors.map((item, idx) => {
                const { Name, Unit, Value } = item;
              return (<span key={idx}><label>{Name}({Unit}): </label>{Value}</span>);
              })
            }
            children = (<div className={styles.item}>
              <strong>{Station.Name}</strong>
              <div className={styles.list}>{child}</div>
            </div>);
          }
        } catch (error) {
          console.error(error)
        }
      } else {
        const { columns } = this.state;
        const dataResource = props[`ScadaTplResource${value}`];
        // 
        try {
          if (Array.isArray(dataResource)) {
            children = dataResource.map((item, idx) => {
              const { station } = item;
              let child = columns.map(col => {
                const { id, name } = col;
                const cols = `C${id}`;
                return (<span key={id}><label>{name}: </label>{item[cols]}</span>)
              });
              const alarmingCls = item['alarming'] ? styles.alarming : '';
              return (<div key={idx} className={styles.item}>
                <strong className={`${alarmingCls}`}>{station.Name}</strong>
                <div className={styles.list}>{child}</div>
              </div>);
            })
          }
        } catch (error) {
          console.error(error)
        }
      }
    }
    return (<div className={styles.Items}>{children}</div>);
  }

  handleChange = async (tab) => {
    this.setState({
      tab,
      loading: true,
    }, async () => {
      await this.queryData();
    })
  }

  render() {
    const { List, state } = this;
    const { activeTab, loading } = state;
    return (<Title title={'在线监测数据展示'} style={{ 'padding': '2%' }}>
      <Tabs
        tabs={List}
        initialPage={activeTab}
        swipeable={false}
        // onChange={e => this.handleChange(e)}
        onTabClick={e => this.handleChange(e)}
        renderTabBar={props => <Tabs.DefaultTabBar
          {...props} page={4} />}
      >
        {this.renderContent}
      </Tabs>
    </Title>)
  }
}

export default Statistics;
